// 自定义验证类: username以“user_”开头为例
import { applyDecorators, Injectable } from '@nestjs/common';
import {
  IsString,
  Validate,
  ValidationArguments,
  ValidatorConstraint,
  ValidatorConstraintInterface,
} from 'class-validator';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from '../entities/user.entity';
import { Repository } from 'typeorm';

@Injectable()
@ValidatorConstraint({ name: 'StartsWith', async: false })
export class StartsWithConstraint implements ValidatorConstraintInterface {
  validate(text: string, args: ValidationArguments) {
    const { constraints } = args;
    return text.startsWith(constraints[0]);
  }

  defaultMessage(args: ValidationArguments) {
    const { property, constraints } = args;
    return `${property} must startsWith ${constraints[0]}`;
  }
}

export function StartsWith(prefix: string) {
  return applyDecorators(IsString(), Validate(StartsWithConstraint, [prefix]));
}

// 通过数据库内查找判断用户名是否唯一的校验
// let userRepository = null; // TODO 临时解决校验中的数据库注入问题

@ValidatorConstraint({ name: 'IsUsernameUnique', async: true })
export class IsUsernameUniqueConstraint
  implements ValidatorConstraintInterface
{
  constructor(@InjectRepository(User) protected repository: Repository<User>) {
    // if (!userRepository) {
    //   userRepository = repository;
    // }
  }

  async validate(text: string, args: ValidationArguments) {
    const isExist = await this.repository.findOneBy({
      username: text,
    });
    return !isExist;
  }

  defaultMessage(args: ValidationArguments) {
    const { property, value } = args;
    return `${property} ${value} is already token!`;
  }
}
